package com.gujia.controller;

import com.gujia.model.Comment;
import com.gujia.model.Question;
import com.gujia.service.CommentService;
import com.gujia.service.QuestionService;
import com.gujia.util.AnswerUtil;
import com.gujia.util.EntityType;
import com.gujia.util.LoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * Created by GuJia on 2017/6/30.
 */
@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private QuestionService questionService;

    @RequestMapping(path={"/comment/add"},method = {RequestMethod.POST})
   // @ResponseBody
    public String addComment(Model model, @RequestParam("questionId") int questionId, @RequestParam("content") String content){


        try{

            Comment comment = new Comment();
            comment.setContent(content);
            comment.setCreatedDate(new Date());
            comment.setEntityId(questionId);
            comment.setEntityType(EntityType.ENTITY_QUESTION);
            comment.setStatus("0");

            if(LoginUtil.getUser() == null){
                //return AnswerUtil.getJSONString(999);
                comment.setUserId(0);
            }else{
                comment.setUserId(LoginUtil.getUserId());
            }

            commentService.addComment(comment);

            int count = commentService.getCommentCount(questionId,EntityType.ENTITY_QUESTION);

            questionService.updateCommentCount(questionId);
        }catch (Exception e){
            e.printStackTrace();

        }

        return "redirect:/question/"+questionId;



    }


}
